package com.xcoder.algorithm.list_search;

/**
 * 二分查找
 * <p>
 * Created by wpq on 2019/12/21.
 */
public class BinarySearch {

    public static void main(String[] args) {
        int[] arr = {1, 3, 5, 6, 8};
        System.out.println(binarySearch(arr, 5));
    }

    private static int binarySearch(int[] arr, int target) {
        if (arr == null || arr.length == 1) {
            return -1;
        }
        int start = 0;
        int end = arr.length - 1;
        while (start <= end) {
            int mid = (start + end) >> 1;
            if (target < arr[mid]) {
                end = mid - 1;
            } else if (target > arr[mid]) {
                start = mid + 1;
            } else {
                return mid;
            }
        }
        return -1;
    }
}
